using UnityEngine;

//[RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))]
public class sector : MonoBehaviour
{
    public float Radius = 2f;          //外半径  
    public float innerRadius = 0.5f;     //内半径
    public float angleDegree = 60;   //扇形或扇面的角度
    public int Segments = 60;         //分割数  
    private static float originOffSetAngle = 0;     //原始旋转角度

    public bool isRatating = false;
    private MeshFilter m_meshPanel;

    private void Start()
    {
        originOffSetAngle = transform.eulerAngles.y;
        m_meshPanel = GetComponent<MeshFilter>();
        m_meshPanel.mesh = CreateSector(Radius, innerRadius, angleDegree, Segments);
    }

    /// 绘扇形图(2d)
    public static Mesh CreateSector(float radius, float innerRadius, float angleDegree, int nbSides)
    {
        int vertices_count = nbSides * 2 + 2;              //因为vertices(顶点)的个数与triangles（索引三角形顶点数）必须匹配
        Vector3[] vertices = new Vector3[vertices_count];
        float angleRad = Mathf.Deg2Rad * (angleDegree);
        float angleRadOffset = Mathf.Deg2Rad * ((180-angleDegree) /2 + originOffSetAngle);//偏移弧度
        float angledelta = angleRad / nbSides;
        float angleCur = angleRad;
        for (int i = 0; i < vertices_count; i += 2)
        {
            float cosA = Mathf.Cos(angleCur + angleRadOffset);
            float sinA = Mathf.Sin(angleCur + angleRadOffset);
            vertices[i] = new Vector3(radius * cosA, 0, radius * sinA);
            vertices[i + 1] = new Vector3(innerRadius * cosA, 0, innerRadius * sinA);
            angleCur -= angledelta;
        }

        //triangles:
        int triangle_count = nbSides * 6;
        int[] triangles = new int[triangle_count];
        for (int i = 0, vi = 0; i < triangle_count; i += 6, vi += 2)
        {
            triangles[i] = vi;
            triangles[i + 1] = vi + 3;
            triangles[i + 2] = vi + 1;
            triangles[i + 3] = vi + 2;
            triangles[i + 4] = vi + 3;
            triangles[i + 5] = vi;
        }

        //uv:
        Vector2[] uvs = new Vector2[vertices_count];
        for (int i = 0; i < vertices_count; i++)
        {
            uvs[i] = new Vector2(vertices[i].x / radius / 2 + 0.5f, vertices[i].z / radius / 2 + 0.5f);
        }

        //负载属性与mesh
        Mesh mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        return mesh;
    }

}